//
//  startMoneyViewController.m
//  ioschishan
//
//  Created by 千翼网络科技 on 2017/7/17.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "startMoneyViewController.h"
#import "startMoneyTableViewCell.h"
#import "startSucessViewController.h"
#import "crowdAgreementViewController.h"

#define HeightVC [UIScreen mainScreen].bounds.size.height//获取设备高度
#define WidthVC [UIScreen mainScreen].bounds.size.width//获取设备宽度

@interface startMoneyViewController ()<UITableViewDelegate , UITableViewDataSource , UITextFieldDelegate>{
    
    float cellHeight;
}

@property(nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong) NSMutableDictionary *dataDic;
@property(nonatomic,strong) UITableView *helpTableView;

@property(nonatomic,strong) UIScrollView *mianScrollView;

@property(nonatomic,strong) UITextField *moneyTextField;
@property(nonatomic,strong) UITextField *wayTextField;
@property(nonatomic,strong) UITextField *dateTextField;
@property(nonatomic,strong) UITextField *nameTextField;
@property(nonatomic,strong) UITextField *titleTextField;
@property(nonatomic,strong) UITextView *messageTextView;
@property(nonatomic,strong) UILabel *locationLabel;

@end

@implementation startMoneyViewController

- (void)viewWillAppear:(BOOL)animated{
    
    if ([[self getBigImageArray] count] < 3) {
        
        cellHeight = 0;
        
    }else if ([[self getBigImageArray] count] < 6){
    
        cellHeight = ([UIScreen mainScreen].bounds.size.width - screenScale(45)) / 3;
        
    }else{
    
        cellHeight = ([UIScreen mainScreen].bounds.size.width  - screenScale(45)) / 3 * 2 + screenScale(30);
        
    }
    [_helpTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}

#pragma mark ------------------ init -------------------

- (void)initView{
    
    self.title = @"发起众筹";
    
    cellHeight = 0;
    
    _helpTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), scrHeight() - 64 - screenScale(44))];
    _helpTableView.backgroundColor = getColor(@"ffffff");
    _helpTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _helpTableView.delegate = self;
    _helpTableView.dataSource = self;
    _helpTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_helpTableView];
    
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(1), scrWidth(), screenScale(0.7))];
    threadView.backgroundColor = getColor(@"cccccc");
    [self.view addSubview:threadView];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, screenScale(60), screenScale(40))];
    rightBtn.titleLabel.font = get4sFont(14);
    rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, screenScale(10), 0, screenScale(-10));
    [rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [rightBtn setTitleColor:getColor(@"3a95ff") forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItme;
    
    ///
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = getColor(@"ffffff");
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(0);
        make.height.offset(screenScale(44));
    }];
    
    UIView *bottomThreadView = [[UIView alloc]init];
    bottomThreadView.backgroundColor = getColor(@"eeeeee");
    [self.view addSubview:bottomThreadView];
    [bottomThreadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(screenScale(-44));
        make.height.offset(screenScale(0.5));
    }];
    
    UIImageView *bottomImg = [[UIImageView alloc]init];
    bottomImg.image = [UIImage imageNamed:@"select_green_icon"];
    [self.view addSubview:bottomImg];
    [bottomImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(screenScale(61));
        make.bottom.equalTo(self.view).with.offset(screenScale(-15));
        make.width.offset(screenScale(14));
        make.height.offset(screenScale(14));
    }];
    
    UILabel *bottomLabel = [ConfigXp labelWithFrame:CGRectZero
                                               text:@"已阅读并同意"
                                          textColor:getColor(@"9b9b9b")
                                               font:get4sFont(11)
                                      textAlignment:NSTextAlignmentLeft
                                    backgroundColor:[UIColor clearColor]];
    [self.view addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(screenScale(-15));
        make.left.equalTo(self.view).with.offset(screenScale(80));
        
        
    }];
    
    UIButton *bottomBtn = [ConfigXp buttonWithFrame:CGRectZero
                                              title:@"《天边彩虹众筹发起条款》"
                                         titleColor:getColor(@"5eca34")
                                               font:get4sFont(11)
                                    backgroundColor:nil
                                              image:nil];
    [bottomBtn addTarget:self action:@selector(bottomBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(screenScale(170));
        make.bottom.equalTo(self.view).with.offset(screenScale(-17));
        make.height.offset(screenScale(12));
        
    }];
    
    UILabel *promptLabel = [[UILabel alloc]init];
    promptLabel.textColor = getColor(@"9b9b9b");
    promptLabel.backgroundColor = getColor(@"ffffff");
    promptLabel.numberOfLines = 2;
    promptLabel.text = @"建议上传家庭经济情况、财产证明和贫穷状况等拍照，提高项目可信度";
    promptLabel.font = get4sFont(11);
    [self.view addSubview:promptLabel];
    [promptLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(bottomThreadView.mas_top).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(screenScale(5));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-5));
        make.height.mas_equalTo(screenScale(44));
    }];
    
    ///
    
    _moneyTextField = [[UITextField alloc]init];
    _moneyTextField.delegate = self;
    
    _wayTextField = [[UITextField alloc]init];
    _wayTextField.delegate = self;
    
    _dateTextField = [[UITextField alloc]init];
    _dateTextField.delegate = self;
    
    _nameTextField = [[UITextField alloc]init];
    _nameTextField.delegate = self;
    
    _titleTextField = [[UITextField alloc]init];
    _titleTextField.delegate = self;
    
    _messageTextView = [[UITextView alloc]init];
    
    _locationLabel = [[UILabel alloc]init];
    
}

#pragma mark -------------------- click ----------------------

- (void)bottomBtnClick{

    crowdAgreementViewController *vc = [[crowdAgreementViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)rightBtnClick{
    
    NSLog(@"%@",self.bigImageArray);
    
    NSLog(@"%@,%@,%@,%@,%@,%@,%@",_moneyTextField.text,_wayTextField.text,_dateTextField.text,_nameTextField.text,_titleTextField.text,_messageTextView.text,_locationLabel.text);
    
    if (_moneyTextField.text.length < 1 || _wayTextField.text.length < 1 || _dateTextField.text.length < 1 || _titleTextField.text.length < 1 || _messageTextView.text.length < 1 || _locationLabel.text.length < 1||
        _nameTextField.text.length < 1 || [_locationLabel.text isEqualToString:@"位置"]) {
        
        [PublicFunction showAlert:nil message:@"信息不完整" duration:1.0];
        return;
        
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams = [[NSMutableDictionary alloc]init];
    [productParams setValue: _classify forKey:@"classify"];
    [productParams setValue: _moneyTextField.text forKey:@"target"];
    [productParams setValue: _wayTextField.text forKey:@"purpose"];
    [productParams setValue: _dateTextField.text forKey:@"days"];
    [productParams setValue: _titleTextField.text forKey:@"title"];
    [productParams setValue: _messageTextView.text forKey:@"content"];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    [productParams setValue: _locationLabel.text forKey:@"city"];
    [productParams setValue: _nameTextField.text forKey:@"school"];
    
    NSLog(@"productParams===\n\n%@",productParams);
    
    //两种方式上传头像
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",nil];
    [manager POST:more_addCrowd parameters:productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSLog(@"\n\n\n===\n\n\n %@ \n\n\n===\n\n\n %@",[self getBigImageArray],[self arrSelected]);
        
        __block NSInteger i = 0;
        
        [[self getBigImageArray] enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            i++;
            
            //压缩图片 - 转为二进制
            NSData *imageData = UIImageJPEGRepresentation(obj,0.01);
            
            //图片大小
            float length2 = [imageData length]/1024;
            NSLog(@"image length===%f",length2);
            
            //拼接图片名称+时间确保不重复命名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.jpg", [formatter stringFromDate:[NSDate date]],i];
            
            //上传图片，以文件流的格式
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"image%ld",i] fileName:imageFileName mimeType:@"image/JPG/png"];
            
        }];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        
        NSLog(@"+++>%@", resultDic);
        NSLog(@"--->%@", resultDic[@"msg"]);
        
        [hud removeFromSuperview];
        
        startSucessViewController *vc = [[startSucessViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"--->%@", error);
        [hud removeFromSuperview];
        
    }];
    
}

- (UIImage *)fixOrientation:(UIImage *)aImage {
    if (aImage.imageOrientation == UIImageOrientationUp)
        
        return aImage;
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

#pragma mark -------------------- tableView ----------------------

#pragma mark --- UITableViewDelegate ---

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return scrHeight() - screenScale(44) - 64 + cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    startMoneyViewController *vc = [[startMoneyViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark --- UITableViewDataSource ---

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView registerClass:[startMoneyTableViewCell class] forCellReuseIdentifier:@"identifier"];
    startMoneyTableViewCell *cell = (startMoneyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _moneyTextField = cell.moneyTextField;
    _wayTextField = cell.wayTextField;
    _dateTextField = cell.dateTextField;
    _nameTextField = cell.nameTextField;
    _titleTextField = cell.titleTextField;
    _messageTextView = cell.messageTextView;
    _locationLabel = cell.locationLabel;
    
    ///
    
    _mianScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, screenScale(367 + 17), WidthVC, HeightVC+530)];
    _mianScrollView.contentSize = CGSizeMake(WidthVC, HeightVC+530);
    _mianScrollView.bounces = YES;
    _mianScrollView.showsVerticalScrollIndicator = false;
    _mianScrollView.backgroundColor = [UIColor whiteColor];
    [cell addSubview:_mianScrollView];
    [_mianScrollView setDelegate:self];
    self.showInView = _mianScrollView;
    self.maxCount = 9;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, scrHeight() - screenScale(44) - 64 - screenScale(30) + ([UIScreen mainScreen].bounds.size.width - screenScale(45)) / 3 * 2, scrWidth(), screenScale(200))];
    view.backgroundColor = [UIColor whiteColor];
    [cell addSubview:view];
    
    [self initPickerView];
    
    

    return cell;
}

@end
